package com.jg.utils.Thread;

import java.util.concurrent.TimeUnit;

/**
 * 3.2.6 死锁
 * 死锁并不是一种锁，而是对锁使用不当产生的bug。
 * 当多个锁交叉使用时，很容易会引起死锁问题，死锁在生产环境中是非常严重的问题，应当坚决杜绝。
 *
 * 我们可以使用JDK自带的工具去检测死锁。
 * 先在命令行执行 jps
 *
 * jstack -l 进程ID
 */
public class Deadlock {
    public static void main(String[] args) throws InterruptedException {
        DieLock oj = new DieLock();
        oj.setUsername("a");
        Thread t1 = new Thread(oj);
        t1.start();
        TimeUnit.SECONDS.sleep(1);
        oj.setUsername("b");
        Thread t2 = new Thread(oj);
        t2.start();
    }

}

class DieLock implements Runnable {
    private String username;
    private final Object lock1 = new Object();
    private final Object lock2 = new Object();
    public void setUsername(String username) {
        this.username = username;
    }
    @Override
    public void run() {
        if (username.equals("a")) {
            synchronized (lock1) {
                System.out.println("username是a1");
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock2) {
                    System.out.println("username是a2");
                }
            }
        }
        if (username.equals("b")) {
            synchronized (lock2) {
                System.out.println("username是b1");
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock1) {
                    System.out.println("username是b2");
                }
            }
        }
    }


}
